import unittest
import random
from kea2 import precondition, prob, max_tries
from hypium import BY, UiDriver


class exploreCase(unittest.TestCase):

    d: "UiDriver"
    # Use class variable to maintain state across test executions
    browsed = False
    # Search keywords
    search_keywords = [
        "开发者故事",
        "技术干货", 
        "鸿蒙生态",
        "应用模型",
        "ArkUI",
        "DevEco Studio"
    ]

    @prob(0.8)
    @precondition(
        lambda self: self.d.find_component(BY.type("SearchField"))
        and self.d.find_component(BY.text("搜索发现"))
    )
    def test_search_random_keyword(self):
        """搜索框输入随机关键词
        """
        if not self.search_keywords:
            print("关键词列表为空")
            return
        print("搜索框 存在")
        comp = self.d.find_component(BY.type("SearchField"))
        comp.clearText()
        keyword = random.choice(self.search_keywords)
        print(f"随机选择关键词: {keyword}，并输入搜索框")
        comp.inputText(keyword)
        print("点击搜索")
        self.d.find_component(BY.id("__SearchField__Image__")).click()

    @max_tries(2)
    @precondition(
        lambda self: self.d.find_component(BY.text("鸿蒙生态"))
    )
    def test_click_information_button(self):
        """浏览咨询页面
        """
        print("热门资讯 模块存在")
        comp = self.d.find_component(BY.text("鸿蒙生态"))
        print("点击: 鸿蒙生态")
        comp.click()
        # Set class variable to maintain state
        exploreCase.browsed = True
        print("browsed: ", exploreCase.browsed)

        # 引导到待测功能场景
        retry_count = 5
        while retry_count > 0:
            retry_count -= 1
            self.d.swipe_to_back()
            if self.d.find_component(BY.text("我的")):
                break
        if retry_count == 0:
            print("未能返回到我的页面，可能是浏览过多页面")
            return
        print("进入 我的 页面")
        self.d.find_component(BY.text("我的")).click()

    @prob(0.8)
    @precondition(
        lambda self: self.d.find_component(BY.text("最新动态"))
    )
    def test_click_dynamics_button(self):
        """点击最新动态按钮(咨询->开发者故事->最新动态)，进入后无法退出
        """
        print("最新动态 按钮存在")
        comp_news = self.d.find_component(BY.text("最新动态"))
        print("点击: 最新动态")
        comp_news.click()
        print("再次点击 最新动态")
        comp_news.click()

    @prob(0.8)
    @precondition(
        lambda self: self.d.find_component(BY.text("浏览"))
        and exploreCase.browsed == True
    )
    def test_read_information_should_be_reported(self):
        """已经浏览过咨询后，“未浏览文章或咨询”应该不存在
        """
        print("浏览 按钮存在")
        comp = self.d.find_component(BY.text("浏览"))
        print("点击: 浏览")
        comp.click()
        assert self.d.find_component(BY.text("去浏览第一篇文章或资讯")) is None, "Error: 未浏览文章或资讯"


if __name__ == "__main__":
    d = UiDriver.connect(
        device_sn = "4ABVB25114010220",
        connector="hdc"
    )
